package com.liu.wode.controller;

import com.liu.wode.mapper.UserMapper;
import com.liu.wode.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @GetMapping("/myUser")
    public String queryUserList(Model model){
        List<User> users = userMapper.queryUserList();
        model.addAttribute("users",users);
        return "user/ulist";
    }

    @GetMapping("/UtoAdd")
    public String toAddUser(){
        return "user/uadd";
    }

    @PostMapping("/UtoAdd")
    public String addUser(@RequestParam("name") String name, @RequestParam("pwd") String pwd, @RequestParam("sex") Integer sex, @RequestParam("IdCard") String IdCard, @RequestParam("phone") String phone){
        int init=0;
        while (userMapper.queryUserById(init)!=null){
            init++;
        }
        System.out.println(sex);
        System.out.println(IdCard);
        System.out.println(phone);
        userMapper.addUser(new User(init,name,pwd,sex,IdCard,phone));
        return "redirect:/myUser";
    }
    @GetMapping("/deluser/{id}")
    public String delUser(@PathVariable("id") Integer id){
        userMapper.delUser(id);
        return "redirect:/myUser";
    }

    @GetMapping("/user/{id}")
    public String toUpdateUser(@PathVariable("id")Integer id,Model model){
        User user = userMapper.queryUserById(id);
        model.addAttribute("user",user);
        return "user/uupdate";
    }
    @PostMapping("/updateUser")
    public String updateUser(User user){
        System.out.println(user);
        userMapper.upUser(user);
        return "redirect:/myUser";
    }

}
